<template>
  <n-card title="拓扑图编辑器" content-style="padding: 0;">
    <div class="topology-editor">
      <div class="editor-layout">
        <!-- 左侧组件面板 -->
        <node-palette
          :node-templates="nodeTemplates"
          @node-select="handleNodeSelect"
          class="node-palette"
        />

        <!-- 右侧画布区域 -->
        <topology-canvas
          :nodes="nodes"
          :edges="edges"
          :selected-node-type="selectedNodeType"
          :node-types="nodeTypes"
          @nodes-change="handleNodesChange"
          @edges-change="handleEdgesChange"
          @node-click="handleNodeClick"
          @edge-click="handleEdgeClick"
          @canvas-click="handleCanvasClick"
          @connect="handleConnect"
          class="topology-canvas"
        />
      </div>

      <!-- AI助手 -->
      <TopologyAIHelper @topology-generated="handleTopologyGenerated" />

      <!-- JSON导入浮动按钮 -->
      <n-float-button
        type="primary"
        @click="showJsonImportModal = true"
        class="json-import-btn"
      >
        <template #icon>
          <n-icon>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 24 24"
              width="18"
              height="18"
            >
              <path
                fill="currentColor"
                d="M19 9h-4V3H9v6H5l7 7l7-7zm-8 2V5h2v6h1.17L12 13.17L9.83 11H11zm-6 7h14v2H5z"
              />
            </svg>
          </n-icon>
        </template>
      </n-float-button>

      <!-- JSON导入弹窗 -->
      <JSONImportModal
        v-model:show="showJsonImportModal"
        @import="handleJsonImport"
      />
    </div>
  </n-card>
</template>

<script setup>
import { ref, markRaw } from "vue";
import { NCard, NFloatButton, NIcon, useMessage } from 'naive-ui';
import NodePalette from "./NodePalette.vue";
import TopologyCanvas from "./TopologyCanvas.vue";
import TopologyAIHelper from "./TopologyAIHelper.vue";
import JSONImportModal from "./JSONImportModal.vue";
import { useTopologyEditor } from "../../composables/useTopologyEditor";
import { nodeTemplates } from "../../utils/nodeTemplates";
import MissileDeviceNode from "./MissileDeviceNode.vue";

const message = useMessage();

// 使用组合式函数管理编辑器状态
const {
  nodes,
  edges,
  selectedNodeType,
  selectedEdge,
  handleNodesChange,
  handleEdgesChange,
  handleNodeClick,
  handleEdgeClick,
  handleCanvasClick,
  handleConnect,
} = useTopologyEditor();

// 节点类型定义
const nodeTypes = {
  missileDevice: markRaw(MissileDeviceNode),
};

// JSON导入相关状态
const showJsonImportModal = ref(false)

// 处理节点选择
const handleNodeSelect = (nodeType) => {
  selectedNodeType.value = nodeType;
};

// 处理AI生成的拓扑数据 - 新增方法
const handleTopologyGenerated = (topologyData) => {
  console.log("接收到的拓扑数据:", topologyData);

  // 清空现有节点和边
  nodes.value = [];
  edges.value = [];

  // 添加新节点和边
  setTimeout(() => {
    nodes.value = topologyData.nodes;
    edges.value = topologyData.edges;
  }, 100);
};

// 动态高度计算函数
const calculateDynamicNodeConfig = (template) => {
  const baseWidth = 200
  const headerHeight = 45
  const connectorTitleHeight = 22
  const pinRowHeight = 24
  
  let totalHeight = headerHeight
  
  template.connectors?.forEach(connector => {
    totalHeight += connectorTitleHeight
    if (connector.pins && connector.pins.length > 0) {
      totalHeight += connector.pins.length * pinRowHeight
    }
  })
  
  totalHeight += 8
  const minHeight = Math.max(140, totalHeight)
  
  return {
    nodeSize: {
      width: baseWidth,
      height: minHeight
    }
  }
}

// 新增：判断是否为完整格式
const isFullFormat = (data) => {
  return data.nodes && 
         data.nodes.length > 0 && 
         data.nodes[0].data && 
         data.edges &&
         data.edges[0].sourceX !== undefined // 完整格式包含坐标
}

// 修改 handleJsonImport 函数
const handleJsonImport = (topologyData) => {
  try {
    console.log('导入的拓扑数据:', topologyData)
    
    let finalNodes = []
    let finalEdges = []
    
    // 判断数据格式
    if (isFullFormat(topologyData)) {
      console.log('检测到完整格式，直接使用')
      // 完整格式：直接使用，不做转换
      finalNodes = topologyData.nodes
      finalEdges = topologyData.edges
    } else {
      console.log('检测到简化格式，进行转换')
      // 简化格式：进行转换
      finalNodes = topologyData.nodes.map(node => {
        const deviceType = node.data?.type || node.type
        const template = nodeTemplates[deviceType]
        
        if (!template) {
          throw new Error(`未知的设备类型: ${deviceType}`)
        }
        
        const { nodeSize } = calculateDynamicNodeConfig(template)
        
        return {
          id: node.id,
          type: "missileDevice",
          position: node.position,
          data: {
            ...template.defaultData,
            label: template.name,
            type: deviceType,
            connectors: template.connectors,
            description: template.description,
            subsystem: template.subsystem
          },
          style: {
            border: `2px solid ${template.color}`,
            borderRadius: "8px",
            background: "white",
            width: `${nodeSize.width}px`,
            height: `${nodeSize.height}px`,
            fontSize: "11px",
            boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
          }
        }
      })
      
      finalEdges = topologyData.edges.map((edge, index) => ({
        id: `edge-${index}-${Date.now()}-${Math.random().toString(36).substr(2, 5)}`,
        source: edge.source,
        target: edge.target,
        sourceHandle: edge.sourcePin || edge.sourceHandle,
        targetHandle: edge.targetPin || edge.targetHandle,
        style: { stroke: '#666' },
        type: 'smoothstep'
      }))
    }
    
    // 清空现有节点和边
    nodes.value = []
    edges.value = []
    
    // 添加新节点和边
    setTimeout(() => {
      nodes.value = finalNodes
      edges.value = finalEdges
      message.success(`成功导入 ${finalNodes.length} 个节点和 ${finalEdges.length} 条边`)
    }, 100)
    
  } catch (error) {
    message.error(`导入失败: ${error.message}`)
    console.error('JSON导入错误:', error)
  }
}
</script>

<style scoped>
.topology-editor {
  width: 100%;
  height: calc(100vh - 136px);
}

.editor-layout {
  display: grid;
  grid-template-columns: 280px 1fr;
  gap: 0;
  height: 100%;
}

.node-palette {
  height: 100%;
  overflow: hidden; /* 隐藏外层滚动条 */
  border-right: 1px solid #e8e8e8;
  background: white;
}

.topology-canvas {
  background: #fafafa;
}
</style>